import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Queue;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2023-05-06
 * Time:21:34
 */

/**
 * BM26 求二叉树的层序遍历
 */

public class levelOrder {
    public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
        // write code here
        ArrayList<ArrayList<Integer>> lists = new ArrayList<>();

        if (root == null){
            return lists;
        }
        Queue<TreeNode> queue = new ArrayDeque<>();

        queue.add(root);

        while (!queue.isEmpty()){
            ArrayList<Integer> list = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                list.add(cur.val);
                if (cur.left != null){
                    queue.add(cur.left);
                }
                if (cur.right != null){
                    queue.add(cur.right);
                }
            }
            lists.add(list);
        }
        return lists;
    }


}
